package com.cysd.ewmksbs.ui.activity

import android.os.Bundle
import android.util.Log
import com.bumptech.glide.Glide
import com.cszy.ewmxns.base.BaseVMActivity
import com.cysd.ewmksbs.service.RecognizeService
import com.cysd.ewmksbs.ui.fragment.Ksb_ScanErrorDialog
import com.cysd.ewmksbs.ksb_utils.ClipboardUtils
import com.cysd.ewmksbs.ksb_utils.FileUtil
import com.cysd.ewmksbs.viewmodel.MainViewModel
import org.json.JSONObject
import com.csylhl.ewmksb.R
import com.csylhl.ewmksb.databinding.ActivityOcrResultBinding


class Ksb_OcrResultActivity : BaseVMActivity<MainViewModel, ActivityOcrResultBinding>() {
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.headTitle.headCenterTitle.text = "提取结果"
    }

    private val errorDialog by lazy {
        Ksb_ScanErrorDialog(this)
    }

    override fun initData() {

        RecognizeService.recGeneralBasic(
            this,
            FileUtil.getSaveFile(this).absolutePath,
            object : RecognizeService.ServiceListener {  // 去掉括号
                override fun onResult(result: String?) {
                    Log.e("qin", "识别结果：$result")
                    mBinding.tvResult.text = parseWithOrgJson(result!!)
                }
            })

        Glide.with(this)
            .load(FileUtil.getSaveFile(this).absolutePath)
            .placeholder(R.mipmap.ic_launcher)
            .error(R.mipmap.ic_launcher)
            .into(mBinding.ivResult)

    }

    override fun initListener() {

        mBinding.headTitle.headBack.setOnClickListener {
            finish()
        }

        mBinding.tvCopy.setOnClickListener {
            ClipboardUtils.copyTextFromTextView(this, mBinding.tvResult) // 默认显示 Toast
        }
    }

    fun parseWithOrgJson(json: String): String {
        if (json.isBlank()) {
            return "暂无识别内容"
        }
        try {
            val jsonObj = JSONObject(json)

            // 检查是否有 words_result 字段
            if (!jsonObj.has("words_result") || jsonObj.isNull("words_result")) {
                return "暂无识别内容"
            }

            val wordsArray = jsonObj.getJSONArray("words_result")

            // 检查数组是否为空
            if (wordsArray.length() == 0) {
                return "暂无识别内容"
            }

            return (0 until wordsArray.length())
                .mapNotNull { index ->
                    try {
                        val wordObj = wordsArray.getJSONObject(index)
                        // 检查是否有 words 字段且不为空
                        if (wordObj.has("words") && !wordObj.isNull("words")) {
                            wordObj.getString("words")
                        } else {
                            null
                        }
                    } catch (e: Exception) {
                        null // 如果获取某个单词失败，返回 null 跳过
                    }
                }
                .filter { it.isNotBlank() } // 过滤空字符串
                .joinToString(" ")
                .ifBlank { "暂无识别内容" } // 如果最终结果为空字符串，返回默认值

        } catch (e: Exception) {
            // 处理 JSON 解析异常
            errorDialog?.show()
            return "解析错误: ${e.message}"
        }
    }
}